import { UpdateBookDto } from './dto/update-book.dto';
import { CreateBookDto } from './dto/create-book.dto';
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { DbService } from 'src/db/db.service';
import { Book } from './dto/book.entity';


function randomNum(){
    return Math.floor(Math.random() * 1000000);
}


@Injectable()
export class BookService {
    @Inject()
    dbService: DbService;
    async list(name?:string) {
        const books:Book[] = await this.dbService.read();
        if(name){
            return books.filter(item => item.name.includes(name));
        }
        return books;
    }

    async findById(id: number) {
        const books:Book[] = await this.dbService.read();
        return books.find(item => item.id === id);
    }

    async create(createBookDto: CreateBookDto) {
        const books:Book[] = await this.dbService.read();
        const book = new Book()
        book.id = randomNum();
        book.name = createBookDto.name;
        book.author = createBookDto.author;
        book.description = createBookDto.description;
        book.cover = createBookDto.cover;
        books.push(book);
        await this.dbService.write(books);
        return book;
    }

    async update(updateBookDto: UpdateBookDto) {
        const books:Book[] = await this.dbService.read();
        const book = books.find(item => item.id === updateBookDto.id);
        if(!book){
            throw new BadRequestException('该图书不存在')
        }
        book.name = updateBookDto.name;
        book.author = updateBookDto.author;
        book.description = updateBookDto.description;
        book.cover = updateBookDto.cover;
        await this.dbService.write(books);
        return book;
    }

    async delete(id: number) {
        const books:Book[] = await this.dbService.read();
        const index = books.findIndex(item => item.id === id);
        if(index === -1){
            throw new BadRequestException('该图书不存在')
        }
        books.splice(index, 1);
        await this.dbService.write(books);

    }
}